import re
from metagpt.actions import Action
from metagpt.logs import logger
import time
from datetime import datetime
import requests

class TranslateCode(Action):
    #! Take as input an line by line annotated C/C++ code and return a Rust code that is a translation of the input C/C++ code. Write the translated code to a file named `main.rs`.
    
    name: str = "TranslateCode"
    
    ROLE_DESCRIPTION: str = """In this team, you are an expert in both C/C++ and Rust programs. You are required to translate the input C/C++ program into a Rust program. The C/C++ program is line-by-line annotated, and you can use that for understanding the code. Think step by step, and eventually aggregate your thoughts in an improved version of the code. Do not ignore any function, class, or macro rule defined in the code or the content of them. Do not add new code that does not exist in the original code, such as printing results. You should give a full translation and only conduct translation. The position where variables are defined and the order of declarations should not be adjusted. You must translate macro definitions in C code into Rust's macros or inline function in Rust code.You must translate the code completely. If you do it well, I will give you 100 dollar. Response must be ended with ```rust \n your_code_here \n ```. """
    
    PROMPT_TEMPLATE: str = """{TEAM_DESCRIPTION}\n{ROLE_DESCRIPTION}
    ## Input
    {input_code}
    ## Your Output
    """
    

    async def run(self, team_desc: str, file_name: str):
        with open(file_name, "r") as f:
            input_code = f.read()
            
        prompt = self.PROMPT_TEMPLATE.format(TEAM_DESCRIPTION=team_desc, ROLE_DESCRIPTION=self.ROLE_DESCRIPTION, input_code=input_code)

        rsp = await self._aask(prompt)

        code_text = TranslateCode.parse_code(rsp)
        
        timestamp = time.time()
        # 将秒数转换为日期和时间
        dt_object = datetime.fromtimestamp(timestamp)
        # 将日期和时间转换为字符串
        human_readable_time = dt_object.strftime("%Y-%m-%d %H:%M:%S")
        data = {"time": human_readable_time,"compare":timestamp,"sender":"translater","receiver":"mainfunc_adder","content":code_text}
        response = requests.post("http://localhost:5400/post_msg",json=data)
        response_data = response.json()
        print(response_data)
        with open("main.rs", "w") as f:
            f.write(code_text)

        return file_name + ";" + "main.rs"
    
    @staticmethod
    def parse_code(rsp):
        pattern = r"```rust(.*)```"
        match = re.search(pattern, rsp, re.DOTALL)
        code_text = match.group(1) if match else rsp
        return code_text
    